package io.github.talelin.latticy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.autoconfigure.exception.ParameterException;
import io.github.talelin.latticy.common.enumeration.OrderStatusEnum;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.common.util.SensitiveDataUtil;
import io.github.talelin.latticy.dto.vip.VipOrderPaymentConfirmDTO;
import io.github.talelin.latticy.mapper.OrderMapper;
import io.github.talelin.latticy.mapper.PaymentRejectRecordMapper;
import io.github.talelin.latticy.model.OrderDO;
import io.github.talelin.latticy.vo.OrderSimplifyVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.VipOrderPaymentConfirmVO;
import io.github.talelin.latticy.vo.VipOrderVO;
import io.github.talelin.latticy.model.CUserDO;
import io.github.talelin.latticy.service.CUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.github.talelin.latticy.model.PaymentRejectRecordDO;

/**
 * 统一订单服务
 * 合并了原有的OrderService和VipOrderService功能
 * 现在所有订单都需要使用支付凭证交易
 */
@Service
public class UnifiedOrderService extends ServiceImpl<OrderMapper, OrderDO> {

    @Autowired
    private PaymentRejectRecordMapper paymentRejectRecordMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private CUserService cUserService;

    @Autowired
    private ObjectMapper objectMapper;

    // ==================== 原有OrderService功能 ====================

    /**
     * 修改订单状态
     */
    public void changeOrderStatus(Integer id, Integer status) {
        OrderDO order = this.getBaseMapper().selectById(id);
        if (order == null) {
            throw new NotFoundException(110000);
        }
        // 检查订单状态
        if (order.getStatus() != OrderStatusEnum.PAID.getValue() && order.getStatus() != OrderStatusEnum.DELIVERED.getValue()) {
            throw new ForbiddenException(110001);
        }
        if (order.getStatus() == OrderStatusEnum.PAID.getValue()) {
            if (status != OrderStatusEnum.DELIVERED.getValue()) {
                throw new ForbiddenException(110002);
            }
            this.getBaseMapper().changeOrderStatus(status, id);
        }
        if (order.getStatus() == OrderStatusEnum.DELIVERED.getValue()) {
            if (status != OrderStatusEnum.FINISHED.getValue()) {
                throw new ForbiddenException(110003);
            }
            this.getBaseMapper().changeOrderStatus(status, id);
        }
    }

    /**
     * 获取订单分页列表
     */
    public IPage<OrderDO> getOrderByPage(Integer count, Integer page) {
        Page<OrderDO> pager = new Page<>(page, count);
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(OrderDO::getId);
        IPage<OrderDO> paging = this.getBaseMapper().selectPage(pager, wrapper);
        return paging;
    }

    /**
     * 搜索订单
     */
    public IPage<OrderDO> search(Integer page, Integer count, String keyword, Date start, Date end) {
        Page<OrderDO> pager = new Page<>(page, count);
        IPage<OrderDO> paging = this.baseMapper.searchOrders(pager, "%" + keyword + "%", start, end);
        return paging;
    }

    /**
     * 转换为简化VO
     */
    public List<OrderSimplifyVO> convertFromDO(List<OrderDO> orders) {
        List<OrderSimplifyVO> orderExpires = new ArrayList<>();
        orders.forEach(order -> {
            Date expireTime = order.getExpiredTime();
            OrderSimplifyVO orderSimplifyVO = new OrderSimplifyVO();
            BeanUtils.copyProperties(order, orderSimplifyVO);
            if (expireTime != null) {
                orderSimplifyVO.setExpired(expireTime.before(new Date()));
            }
            orderSimplifyVO.setPrepayId(SensitiveDataUtil.defaultHide(orderSimplifyVO.getPrepayId()));
            orderExpires.add(orderSimplifyVO);
        });
        return orderExpires;
    }

    // ==================== 原有VipOrderService功能 ====================

    /**
     * 获取订单分页列表（支持类型过滤）
     */
    public PageResponseVO<VipOrderVO> getOrderPage(Integer page, Integer count, String status, String keyword, String type) {
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        
        // 如果指定了类型，则过滤类型
        if (type != null && !type.isEmpty()) {
            wrapper.eq("type", type);
        }
        
        if (status != null && !status.isEmpty()) {
            wrapper.eq("status", Integer.parseInt(status));
        }
        
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(w -> w.like("order_no", keyword)
                    .or().like("snap_title", keyword));
        }
        
        wrapper.orderByDesc("create_time");
        
        long total = this.count(wrapper);
        List<OrderDO> orders = this.list(wrapper);
        List<VipOrderVO> vos = convertToVOList(orders);
        
        return new PageResponseVO<>(total, vos, page, count);
    }

    /**
     * 获取订单详情
     */
    public VipOrderVO getOrderDetail(Long id) {
        OrderDO order = this.getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        return convertToVO(order);
    }

    /**
     * 获取支付待确认订单列表
     */
    public PageResponseVO<VipOrderPaymentConfirmVO> getPaymentPendingOrders(Integer page, Integer count, String status) {
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        // 查询待支付(status=1)或已支付(status=2)但需要确认的订单
        wrapper.and(w -> w.eq("status", 1).or().eq("status", 2));
        
        if (status != null && !status.isEmpty()) {
            if ("pending".equals(status)) {
                wrapper.eq("checked", 0); // 待确认
            } else if ("confirmed".equals(status)) {
                wrapper.eq("checked", 1); // 已确认
            } else if ("rejected".equals(status)) {
                wrapper.eq("checked", 2); // 已拒绝
            }
        }
        
        wrapper.orderByDesc("create_time");
        
        long total = this.count(wrapper);
        List<OrderDO> orders = this.list(wrapper);
        List<VipOrderPaymentConfirmVO> vos = convertToPaymentConfirmVOList(orders);
        
        return new PageResponseVO<>(total, vos, page, count);
    }

    /**
     * 获取支付详情
     */
    public VipOrderPaymentConfirmVO getPaymentDetail(Long id) {
        OrderDO order = this.getById(id);
        if (order == null) {
            throw new ParameterException("订单不存在");
        }
        
        // 使用批量查询方法获取支付凭证信息
        List<OrderDO> orders = Arrays.asList(order);
        List<VipOrderPaymentConfirmVO> vos = convertToPaymentConfirmVOList(orders);
        
        if (vos.isEmpty()) {
            throw new ParameterException("订单详情获取失败");
        }
        
        return vos.get(0);
    }

    /**
     * 确认支付
     */
    @Transactional
    public void confirmPayment(Long id, VipOrderPaymentConfirmDTO dto) {
        OrderDO order = this.getById(id);
        if (order == null) {
            throw new ParameterException("订单不存在");
        }
        
        if (order.getChecked() != null && order.getChecked() != 0) {
            throw new ParameterException("订单已审核，不能重复操作");
        }
        
        order.setChecked(1); // 已确认
        order.setPayAmount(dto.getPayAmount()); // 设置确认的支付金额
        order.setUpdateTime(new Date());
        
        // 更新订单
        this.updateById(order);
    }

    /**
     * 拒绝支付
     */
    @Transactional
    public void rejectPayment(Long id, VipOrderPaymentConfirmDTO dto) {
        OrderDO order = this.getById(id);
        if (order == null) {
            throw new ParameterException("订单不存在");
        }
        
        if (order.getChecked() != null && order.getChecked() != 0) {
            throw new ParameterException("订单已审核，不能重复操作");
        }
        
        order.setChecked(2); // 已拒绝
        order.setUpdateTime(new Date());
        
        // 更新订单
        this.updateById(order);
        
        // 创建拒绝记录
        PaymentRejectRecordDO rejectRecord = new PaymentRejectRecordDO();
        rejectRecord.setOrderId(id.longValue());
        rejectRecord.setRejectReason(dto.getRemark() != null ? dto.getRemark() : "订单被拒绝");
        rejectRecord.setReceivedAmount(dto.getPayAmount());
        rejectRecord.setExpectedAmount(order.getFinalTotalPrice());
        rejectRecord.setRejectTime(LocalDateTime.now());
        rejectRecord.setRejectBy(dto.getAuditorId() != null ? dto.getAuditorId() : 0L);
        rejectRecord.setRemark(dto.getRemark());
        rejectRecord.setCreateTime(LocalDateTime.now());
        rejectRecord.setUpdateTime(LocalDateTime.now());
        
        // 保存拒绝记录
        try {
            paymentRejectRecordMapper.insert(rejectRecord);
        } catch (Exception e) {
            // 如果创建拒绝记录失败，记录错误但不影响主流程
            System.err.println("创建拒绝记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取支付审核统计
     */
    public Map<String, Object> getPaymentStats() {
        // 待确认数量
        QueryWrapper<OrderDO> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.and(w -> w.eq("status", 1).or().eq("status", 2)).eq("checked", 0);
        Integer pendingCount = this.count(pendingWrapper);
        
        // 已确认数量
        QueryWrapper<OrderDO> confirmedWrapper = new QueryWrapper<>();
        confirmedWrapper.and(w -> w.eq("status", 1).or().eq("status", 2)).eq("checked", 1);
        Integer confirmedCount = this.count(confirmedWrapper);
        
        // 已拒绝数量
        QueryWrapper<OrderDO> rejectedWrapper = new QueryWrapper<>();
        rejectedWrapper.and(w -> w.eq("status", 1).or().eq("status", 2)).eq("checked", 2);
        Integer rejectedCount = this.count(rejectedWrapper);
        
        // 总数量
        QueryWrapper<OrderDO> totalWrapper = new QueryWrapper<>();
        totalWrapper.and(w -> w.eq("status", 1).or().eq("status", 2));
        Integer totalCount = this.count(totalWrapper);
        
        Map<String, Object> result = new HashMap<>();
        result.put("pending", pendingCount);
        result.put("confirmed", confirmedCount);
        result.put("rejected", rejectedCount);
        result.put("total", totalCount);
        return result;
    }

    /**
     * 批量确认支付
     */
    @Transactional
    public void batchConfirmPayment(List<Long> orderIds, String remark) {
        for (Long orderId : orderIds) {
            VipOrderPaymentConfirmDTO dto = new VipOrderPaymentConfirmDTO();
            dto.setRemark(remark);
            confirmPayment(orderId, dto);
        }
    }

    /**
     * 批量拒绝支付
     */
    @Transactional
    public void batchRejectPayment(List<Long> orderIds, String remark) {
        for (Long orderId : orderIds) {
            VipOrderPaymentConfirmDTO dto = new VipOrderPaymentConfirmDTO();
            dto.setRemark(remark);
            rejectPayment(orderId, dto);
        }
    }

    // ==================== 转换方法 ====================

    /**
     * 转换为VO
     */
    private VipOrderVO convertToVO(OrderDO order) {
        VipOrderVO vo = new VipOrderVO();
        vo.setId(order.getId().longValue());
        vo.setOrderNo(order.getOrderNo());
        vo.setUserId(order.getUserId().longValue());
        vo.setSalerId(order.getSaler() != null ? order.getSaler().longValue() : null);
        vo.setSnapTitle(order.getSnapTitle());
        vo.setSnapImg(order.getSnapImg());
        vo.setTotalPrice(order.getTotalPrice());
        vo.setFinalTotalPrice(order.getFinalTotalPrice());
        vo.setPayAmount(order.getPayAmount());
        vo.setTotalCount(order.getTotalCount() != null ? order.getTotalCount().longValue() : 0L);
        vo.setStatus(order.getStatus());
        vo.setStatusText(getStatusText(order.getStatus()));
        vo.setChecked(order.getChecked());
        vo.setCheckedText(getCheckedText(order.getChecked()));
        vo.setPayImage(order.getPay_image());
        vo.setCreateTime(convertToLocalDateTime(order.getCreateTime()));
        vo.setUpdateTime(convertToLocalDateTime(order.getUpdateTime()));
        vo.setExpiredTime(convertToLocalDateTime(order.getExpiredTime()));
        vo.setExpired(isExpired(convertToLocalDateTime(order.getExpiredTime())));
        return vo;
    }

    /**
     * 转换为VO列表
     */
    private List<VipOrderVO> convertToVOList(List<OrderDO> orders) {
        return orders.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    /**
     * 转换为支付确认VO
     */
    private VipOrderPaymentConfirmVO convertToPaymentConfirmVO(OrderDO order) {
        VipOrderPaymentConfirmVO vo = new VipOrderPaymentConfirmVO();
        vo.setId(order.getId().longValue());
        vo.setOrderNo(order.getOrderNo());
        
        // 买家信息
        VipOrderPaymentConfirmVO.BuyerInfo buyerInfo = new VipOrderPaymentConfirmVO.BuyerInfo();
        buyerInfo.setUserId(order.getUserId().longValue());
        vo.setBuyerInfo(buyerInfo);
        
        // 卖家信息
        VipOrderPaymentConfirmVO.SellerInfo sellerInfo = new VipOrderPaymentConfirmVO.SellerInfo();
        sellerInfo.setSalerId(order.getSaler() != null ? order.getSaler().longValue() : null);
        vo.setSellerInfo(sellerInfo);
        
        // 商品信息
        VipOrderPaymentConfirmVO.ProductInfo productInfo = new VipOrderPaymentConfirmVO.ProductInfo();
        productInfo.setTitle(order.getSnapTitle());
        productInfo.setImage(order.getSnapImg());
        productInfo.setCount(order.getTotalCount() != null ? order.getTotalCount().longValue() : 0L);
        productInfo.setTotalPrice(order.getTotalPrice());
        vo.setProductInfo(productInfo);
        
        // 支付信息
        VipOrderPaymentConfirmVO.PaymentInfo paymentInfo = new VipOrderPaymentConfirmVO.PaymentInfo();
        paymentInfo.setAmount(order.getFinalTotalPrice());
        paymentInfo.setPayAmount(order.getPayAmount());
        paymentInfo.setPayImage(order.getPay_image());
        paymentInfo.setPaymentStatus(getCheckedText(order.getChecked()));
        vo.setPaymentInfo(paymentInfo);
        
        // 审核信息
        VipOrderPaymentConfirmVO.AuditInfo auditInfo = new VipOrderPaymentConfirmVO.AuditInfo();
        vo.setAuditInfo(auditInfo);
        
        // 时间信息
        VipOrderPaymentConfirmVO.TimeInfo timeInfo = new VipOrderPaymentConfirmVO.TimeInfo();
        timeInfo.setCreateTime(convertToLocalDateTime(order.getCreateTime()));
        timeInfo.setUpdateTime(convertToLocalDateTime(order.getUpdateTime()));
        timeInfo.setExpiredTime(convertToLocalDateTime(order.getExpiredTime()));
        timeInfo.setExpired(isExpired(convertToLocalDateTime(order.getExpiredTime())));
        vo.setTimeInfo(timeInfo);

        // 支付凭证信息将在批量查询中设置
        
        // 如果订单被拒绝，添加拒绝记录信息
        if (order.getChecked() != null && order.getChecked() == 2) {
            try {
                // 从payment_reject_record表查询真实的拒绝记录
                QueryWrapper<PaymentRejectRecordDO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", order.getId())
                           .orderByDesc("reject_time");
                List<PaymentRejectRecordDO> rejectRecords = paymentRejectRecordMapper.selectList(queryWrapper);
                
                if (rejectRecords != null && !rejectRecords.isEmpty()) {
                    // 使用最新的拒绝记录
                    PaymentRejectRecordDO latestRejectRecord = rejectRecords.get(0);
                    
                    VipOrderPaymentConfirmVO.RejectionInfo rejectionInfo = new VipOrderPaymentConfirmVO.RejectionInfo();
                    rejectionInfo.setRejectReason(latestRejectRecord.getRejectReason());
                    rejectionInfo.setRejectTime(latestRejectRecord.getRejectTime());
                    rejectionInfo.setRejectBy(latestRejectRecord.getRejectBy());
                    rejectionInfo.setRejectByName("用户" + latestRejectRecord.getRejectBy());
                    rejectionInfo.setReceivedAmount(latestRejectRecord.getReceivedAmount());
                    rejectionInfo.setExpectedAmount(latestRejectRecord.getExpectedAmount());
                    vo.setRejectionInfo(rejectionInfo);
                } else {
                    // 如果没有找到拒绝记录，使用订单中的基本信息作为备选
                    VipOrderPaymentConfirmVO.RejectionInfo rejectionInfo = new VipOrderPaymentConfirmVO.RejectionInfo();
                    rejectionInfo.setRejectReason("订单被拒绝");
                    rejectionInfo.setRejectTime(convertToLocalDateTime(order.getUpdateTime()));
                    rejectionInfo.setRejectBy(null);
                    rejectionInfo.setRejectByName("系统");
                    rejectionInfo.setReceivedAmount(order.getPayAmount());
                    rejectionInfo.setExpectedAmount(order.getFinalTotalPrice());
                    vo.setRejectionInfo(rejectionInfo);
                }
            } catch (Exception e) {
                // 如果查询拒绝记录失败，使用订单中的基本信息作为备选
                VipOrderPaymentConfirmVO.RejectionInfo rejectionInfo = new VipOrderPaymentConfirmVO.RejectionInfo();
                rejectionInfo.setRejectReason("订单被拒绝");
                rejectionInfo.setRejectTime(convertToLocalDateTime(order.getUpdateTime()));
                rejectionInfo.setRejectBy(null);
                rejectionInfo.setRejectByName("系统");
                rejectionInfo.setReceivedAmount(order.getPayAmount());
                rejectionInfo.setExpectedAmount(order.getFinalTotalPrice());
                vo.setRejectionInfo(rejectionInfo);
                
                // 记录错误日志，但不影响主流程
                System.err.println("查询拒绝记录失败: " + e.getMessage());
            }
        }
        
        return vo;
    }

    /**
     * 转换为支付确认VO列表
     */
    private List<VipOrderPaymentConfirmVO> convertToPaymentConfirmVOList(List<OrderDO> orders) {
        if (orders.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 批量查询支付凭证信息，避免N+1查询问题
        Map<Long, VipOrderPaymentConfirmVO.PaymentProofInfo> paymentProofMap = batchGetPaymentProofInfo(
            orders.stream().map(order -> order.getId().longValue()).collect(Collectors.toList())
        );
        
        // 批量查询用户信息，避免N+1查询问题
        Map<Long, CUserDO> userMap = batchGetUserInfo(
            orders.stream()
                .flatMap(order -> Stream.of(order.getUserId().longValue(), order.getSaler() != null ? order.getSaler().longValue() : null))
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList())
        );
        
        return orders.stream().map(order -> {
            VipOrderPaymentConfirmVO vo = convertToPaymentConfirmVO(order);
            
            // 设置买家信息
            CUserDO buyer = userMap.get(order.getUserId().longValue());
            if (buyer != null && vo.getBuyerInfo() != null) {
                vo.getBuyerInfo().setUserNickname(buyer.getNickname());
                vo.getBuyerInfo().setUserAvatar(buyer.getWxProfile() != null ? (String) buyer.getWxProfile().get("avatar") : null);
                vo.getBuyerInfo().setUserPhone(buyer.getMobile());
                vo.getBuyerInfo().setMerchantName(buyer.getRealName()); // 使用realName作为商户名
            }
            
            // 设置卖家信息
            if (order.getSaler() != null) {
                CUserDO seller = userMap.get(order.getSaler().longValue());
                if (seller != null && vo.getSellerInfo() != null) {
                    vo.getSellerInfo().setSalerNickname(seller.getNickname());
                    vo.getSellerInfo().setSalerAvatar(seller.getWxProfile() != null ? (String) seller.getWxProfile().get("avatar") : null);
                    vo.getSellerInfo().setSalerPhone(seller.getMobile());
                    vo.getSellerInfo().setMerchantName(seller.getRealName()); // 使用realName作为商户名
                }
            }
            
            // 设置支付凭证信息
            VipOrderPaymentConfirmVO.PaymentProofInfo paymentProofInfo = paymentProofMap.get(order.getId().longValue());
            vo.setPaymentProofInfo(paymentProofInfo);
            
            // 调试：打印最终返回的数据
            System.out.println("订单 " + order.getId() + " 的支付凭证信息: " + 
                (paymentProofInfo != null ? 
                    "ID=" + paymentProofInfo.getPaymentProofId() + 
                    ", VideoURL=" + paymentProofInfo.getVideoUrl() + 
                    ", Status=" + paymentProofInfo.getVerificationStatus() : 
                    "null"));
            
            return vo;
        }).collect(Collectors.toList());
    }

    // ==================== 工具方法 ====================

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待支付";
            case 1: return "待审核";
            case 2: return "已支付";
            case 3: return "已发货";
            case 4: return "已完成";
            case 5: return "已取消";
            default: return "未知";
        }
    }

    /**
     * 获取确认状态文本
     */
    private String getCheckedText(Integer checked) {
        if (checked == null) return "待确认";
        switch (checked) {
            case 0: return "待确认";
            case 1: return "已确认";
            case 2: return "已拒绝";
            default: return "待确认";
        }
    }

    /**
     * 判断是否过期
     */
    private Boolean isExpired(LocalDateTime expiredTime) {
        if (expiredTime == null) return false;
        return LocalDateTime.now().isAfter(expiredTime);
    }

    /**
     * Date转LocalDateTime
     */
    private LocalDateTime convertToLocalDateTime(Date date) {
        if (date == null) return null;
        return date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 批量获取支付凭证信息
     */
    private Map<Long, VipOrderPaymentConfirmVO.PaymentProofInfo> batchGetPaymentProofInfo(List<Long> orderIds) {
        Map<Long, VipOrderPaymentConfirmVO.PaymentProofInfo> result = new HashMap<>();
        
        if (orderIds.isEmpty()) {
            return result;
        }
        
        try {
            // 构建IN查询条件
            String placeholders = orderIds.stream().map(id -> "?").collect(Collectors.joining(","));
            String sql = "SELECT id, order_id, user_id, saler_id, video_url, verification_status, verification_result, " +
                        "force_submit, force_submit_reason, manual_audit_status, manual_audit_remark, " +
                        "auditor_id, auditor_name, manual_audit_time, create_time " +
                        "FROM payment_proof WHERE order_id IN (" + placeholders + ") ORDER BY order_id, create_time DESC";
            
            System.out.println("查询支付凭证SQL: " + sql);
            System.out.println("查询参数: " + java.util.Arrays.toString(orderIds.toArray()));
            
            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, orderIds.toArray());
            
            System.out.println("查询结果数量: " + results.size());
            for (Map<String, Object> row : results) {
                System.out.println("支付凭证数据: " + row);
            }
            
            // 按order_id分组，每个订单只取最新的支付凭证
            Map<Long, List<Map<String, Object>>> groupedResults = results.stream()
                .collect(Collectors.groupingBy(row -> getLongValue(row.get("order_id"))));
            
            for (Map.Entry<Long, List<Map<String, Object>>> entry : groupedResults.entrySet()) {
                Long orderId = entry.getKey();
                List<Map<String, Object>> orderProofs = entry.getValue();
                
                if (!orderProofs.isEmpty()) {
                    // 取最新的支付凭证（已按create_time DESC排序）
                    Map<String, Object> row = orderProofs.get(0);
                    VipOrderPaymentConfirmVO.PaymentProofInfo paymentProofInfo = parsePaymentProofInfo(row);
                    result.put(orderId, paymentProofInfo);
                }
            }
            
        } catch (Exception e) {
            System.err.println("批量查询支付凭证信息失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 解析支付凭证信息
     */
    private VipOrderPaymentConfirmVO.PaymentProofInfo parsePaymentProofInfo(Map<String, Object> row) {
        System.out.println("解析支付凭证数据: " + row);
        
        VipOrderPaymentConfirmVO.PaymentProofInfo paymentProofInfo = new VipOrderPaymentConfirmVO.PaymentProofInfo();
        
        // 基本信息
        Long id = getLongValue(row.get("id"));
        String videoUrl = getStringValue(row.get("video_url"));
        String verificationStatus = getStringValue(row.get("verification_status"));
        
        System.out.println("解析结果 - ID: " + id + ", VideoURL: " + videoUrl + ", Status: " + verificationStatus);
        
        paymentProofInfo.setPaymentProofId(id);
        paymentProofInfo.setVideoUrl(videoUrl);
        paymentProofInfo.setVerificationStatus(verificationStatus);
        paymentProofInfo.setForceSubmit(getBooleanValue(row.get("force_submit")));
        paymentProofInfo.setForceSubmitReason(getStringValue(row.get("force_submit_reason")));
        paymentProofInfo.setManualAuditStatus(getStringValue(row.get("manual_audit_status")));
        paymentProofInfo.setManualAuditRemark(getStringValue(row.get("manual_audit_remark")));
        paymentProofInfo.setAuditorId(getLongValue(row.get("auditor_id")));
        paymentProofInfo.setAuditorName(getStringValue(row.get("auditor_name")));
        paymentProofInfo.setAuditTime(getLocalDateTimeValue(row.get("manual_audit_time")));
        paymentProofInfo.setCreateTime(getLocalDateTimeValue(row.get("create_time")));
        
        // 解析验证结果
        String verificationResultJson = getStringValue(row.get("verification_result"));
        if (verificationResultJson != null && !verificationResultJson.trim().isEmpty()) {
            try {
                Map<String, Object> verificationResultMap = objectMapper.readValue(verificationResultJson, new TypeReference<Map<String, Object>>() {});
                VipOrderPaymentConfirmVO.VerificationResult verificationResult = parseVerificationResult(verificationResultMap);
                paymentProofInfo.setVerificationResult(verificationResult);
                
                // 从验证结果中提取用户备注
                if (verificationResultMap.containsKey("userRemark")) {
                    paymentProofInfo.setUserRemark(getStringValue(verificationResultMap.get("userRemark")));
                }
            } catch (Exception e) {
                System.err.println("解析验证结果失败: " + e.getMessage());
            }
        }
        
        return paymentProofInfo;
    }

    /**
     * 获取支付凭证信息（单个查询，保留用于兼容性）
     */
    private VipOrderPaymentConfirmVO.PaymentProofInfo getPaymentProofInfo(Long orderId) {
        try {
            String sql = "SELECT id, order_id, user_id, saler_id, video_url, verification_status, verification_result, " +
                        "force_submit, force_submit_reason, manual_audit_status, manual_audit_remark, " +
                        "auditor_id, auditor_name, manual_audit_time, create_time " +
                        "FROM payment_proof WHERE order_id = ? ORDER BY create_time DESC LIMIT 1";
            
            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, orderId);
            
            if (results.isEmpty()) {
                return null;
            }
            
            Map<String, Object> row = results.get(0);
            VipOrderPaymentConfirmVO.PaymentProofInfo paymentProofInfo = new VipOrderPaymentConfirmVO.PaymentProofInfo();
            
            // 基本信息
            paymentProofInfo.setPaymentProofId(getLongValue(row.get("id")));
            paymentProofInfo.setVideoUrl(getStringValue(row.get("video_url")));
            paymentProofInfo.setVerificationStatus(getStringValue(row.get("verification_status")));
            paymentProofInfo.setForceSubmit(getBooleanValue(row.get("force_submit")));
            paymentProofInfo.setForceSubmitReason(getStringValue(row.get("force_submit_reason")));
            paymentProofInfo.setManualAuditStatus(getStringValue(row.get("manual_audit_status")));
            paymentProofInfo.setManualAuditRemark(getStringValue(row.get("manual_audit_remark")));
            paymentProofInfo.setAuditorId(getLongValue(row.get("auditor_id")));
            paymentProofInfo.setAuditorName(getStringValue(row.get("auditor_name")));
            paymentProofInfo.setAuditTime(getLocalDateTimeValue(row.get("manual_audit_time")));
            paymentProofInfo.setCreateTime(getLocalDateTimeValue(row.get("create_time")));
            
            // 解析验证结果
            String verificationResultJson = getStringValue(row.get("verification_result"));
            if (verificationResultJson != null && !verificationResultJson.trim().isEmpty()) {
                try {
                    Map<String, Object> verificationResultMap = objectMapper.readValue(verificationResultJson, new TypeReference<Map<String, Object>>() {});
                    VipOrderPaymentConfirmVO.VerificationResult verificationResult = parseVerificationResult(verificationResultMap);
                    paymentProofInfo.setVerificationResult(verificationResult);
                    
                    // 从验证结果中提取用户备注
                    if (verificationResultMap.containsKey("userRemark")) {
                        paymentProofInfo.setUserRemark(getStringValue(verificationResultMap.get("userRemark")));
                    }
                } catch (Exception e) {
                    System.err.println("解析验证结果失败: " + e.getMessage());
                }
            }
            
            return paymentProofInfo;
            
        } catch (Exception e) {
            System.err.println("查询支付凭证信息失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 解析验证结果
     */
    private VipOrderPaymentConfirmVO.VerificationResult parseVerificationResult(Map<String, Object> verificationResultMap) {
        VipOrderPaymentConfirmVO.VerificationResult verificationResult = new VipOrderPaymentConfirmVO.VerificationResult();
        
        // 解析账单信息
        if (verificationResultMap.containsKey("billInfo")) {
            @SuppressWarnings("unchecked")
            Map<String, Object> billInfoMap = (Map<String, Object>) verificationResultMap.get("billInfo");
            VipOrderPaymentConfirmVO.BillInfo billInfo = new VipOrderPaymentConfirmVO.BillInfo();
            billInfo.setPayeeName(getStringValue(billInfoMap.get("payeeName")));
            billInfo.setOrderNumber(getStringValue(billInfoMap.get("orderNumber")));
            billInfo.setPaymentAmount(getBigDecimalValue(billInfoMap.get("paymentAmount")));
            billInfo.setPaymentTime(getStringValue(billInfoMap.get("paymentTime")));
            billInfo.setPaymentMethod(getStringValue(billInfoMap.get("paymentMethod")));
            billInfo.setIsBillQuery(getBooleanValue(billInfoMap.get("isBillQuery")));
            billInfo.setIsFromDesktop(getBooleanValue(billInfoMap.get("isFromDesktop")));
            billInfo.setConfidence(getDoubleValue(billInfoMap.get("confidence")));
            verificationResult.setBillInfo(billInfo);
        }
        
        // 解析验证信息
        if (verificationResultMap.containsKey("verification")) {
            @SuppressWarnings("unchecked")
            Map<String, Object> verificationMap = (Map<String, Object>) verificationResultMap.get("verification");
            VipOrderPaymentConfirmVO.Verification verification = new VipOrderPaymentConfirmVO.Verification();
            verification.setVerificationStatus(getStringValue(verificationMap.get("verificationStatus")));
            verification.setPayeeMatch(getBooleanValue(verificationMap.get("payeeMatch")));
            verification.setOrderDuplicate(getBooleanValue(verificationMap.get("orderDuplicate")));
            verification.setMerchantName(getStringValue(verificationMap.get("merchantName")));
            verification.setPaymentProofId(getLongValue(verificationMap.get("paymentProofId")));
            verificationResult.setVerification(verification);
        }
        
        verificationResult.setOverallSuccess(getBooleanValue(verificationResultMap.get("overallSuccess")));
        
        return verificationResult;
    }

    // 工具方法
    private String getStringValue(Object value) {
        return value != null ? value.toString() : null;
    }

    private Long getLongValue(Object value) {
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private Boolean getBooleanValue(Object value) {
        if (value == null) return null;
        if (value instanceof Boolean) {
            return (Boolean) value;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        }
        return Boolean.parseBoolean(value.toString());
    }

    private Double getDoubleValue(Object value) {
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        try {
            return Double.parseDouble(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private BigDecimal getBigDecimalValue(Object value) {
        if (value == null) return null;
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private LocalDateTime getLocalDateTimeValue(Object value) {
        if (value == null) return null;
        if (value instanceof LocalDateTime) {
            return (LocalDateTime) value;
        }
        if (value instanceof java.sql.Timestamp) {
            return ((java.sql.Timestamp) value).toLocalDateTime();
        }
        try {
            return LocalDateTime.parse(value.toString());
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 批量查询用户信息
     */
    private Map<Long, CUserDO> batchGetUserInfo(List<Long> userIds) {
        if (userIds.isEmpty()) {
            return new HashMap<>();
        }
        
        try {
            List<CUserDO> users = cUserService.listByIds(userIds);
            return users.stream().collect(Collectors.toMap(
                user -> user.getId().longValue(),
                user -> user
            ));
        } catch (Exception e) {
            System.err.println("批量查询用户信息失败: " + e.getMessage());
            return new HashMap<>();
        }
    }
}
